package com.code2roc.jarmanage.util;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class SQLBuilder {

    public static <T> String buildInsertSQL(String tableName, T entity) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into  " + tableName + " ");
        StringBuilder fieldbuilder = new StringBuilder();
        StringBuilder valuebuilder = new StringBuilder();
        fieldbuilder.append("(");
        valuebuilder.append("(");
        List<Field> fs = Arrays.asList(entity.getClass().getDeclaredFields());
        try {
            for (Field f : fs) {
                f.setAccessible(true);
                if (fs.indexOf(f) == fs.size() - 1) {
                    fieldbuilder.append(f.getName());
                    valuebuilder.append("'" + ConvertUtil.convert2String(f.get(entity)) + "'");
                } else {
                    fieldbuilder.append(f.getName() + ",");
                    valuebuilder.append("'" + ConvertUtil.convert2String(f.get(entity)) + "',");
                }
            }
        } catch (Exception e) {
            LogUtil.error(e);
        }
        fieldbuilder.append(")");
        valuebuilder.append(")");
        sql.append(" " + fieldbuilder.toString());
        sql.append(" values " + valuebuilder.toString());
        return sql.toString();
    }

    public static <T> String buildUpdateSQL(String tableName, T entity, String fieldName) {
        StringBuilder sql = new StringBuilder();
        sql.append("update  " + tableName + " set");
        List<Field> fs = Arrays.asList(entity.getClass().getDeclaredFields());
        try {
            for (Field f : fs) {
                f.setAccessible(true);
                if (fs.indexOf(f) == fs.size() - 1) {
                    sql.append(" " + f.getName() + "='" + ConvertUtil.convert2String(f.get(entity)) + "'");
                } else {
                    sql.append(" " + f.getName() + "='" + ConvertUtil.convert2String(f.get(entity)) + "',");
                }
            }
            Field keyFiled = entity.getClass().getDeclaredField(fieldName);
            keyFiled.setAccessible(true);
            sql.append(" where " + fieldName + "='" +  ConvertUtil.convert2String(keyFiled.get(entity)) + "'");
        } catch (Exception e) {
            LogUtil.error(e);
        }
        return sql.toString();
    }
}
